
#include <cassert>
#include "auto_index_reply.h"
#include "fs/path.h"
#include "fs/directory.h"
#include "utils.h"

using fs::Path;

AutoIndexReply::AutoIndexReply(const fs::Path &path )
{
	assert( path.is_directory() );

	status_code( SC_OK );

	std::string index;
	index += "<html>";
	index += "<head>";
	index += "<title>Listing of direcory</title>";
	index += "</head>";
	index += "<body>";
	index += "<h1>Listing of directory " + path.as_string() + "</h1>";
	index += "<table border=\"0\" width=\"100%\" cellpadding=\"0\">";

	for( fs::DirectoryIterator it( path ); it != fs::DirectoryIterator(); ++it )
	{
		if( it->name() != "." )
		{
			Path node_full_path = path + Path( it->name() );
			std::string nodename = it->name();
			if( node_full_path.is_directory() )
			{
				nodename = nodename + "/";
			}
			
			index += "<tr>";
			index += "<td><a href = " + nodename + ">" + nodename + "</a></td>";
			index += "</tr>";
		}
	}

	index += "</table>";
	index += "</body></html>";

	std::swap( _reply, index );
	headers.set( "Content-Length", itoa( _reply.size() ) );
	headers.set( "Content-Type", "text/html" );
}

void AutoIndexReply::send_body( sock::ClientSocket & sock )
{
	sock.write( _reply.data(), _reply.size() );
}
